<?php

namespace Gds\ArticleBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Gds\ArticleBundle\Entity\Article;
use Gds\ArticleBundle\Form\ArticleType;
use Symfony\Component\HttpFoundation\Response;
use Gds\ArticleBundle\Entity\Stock;

class ArticleController extends Controller {

    public function indexAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        
        $reference = $request->get('reference');
        $designation = $request->get('designation');
        $code_barre = $request->get('code_barre');
        $famille = $request->get('famille');
        $query = $em->getRepository('GdsArticleBundle:Article')->getResult($reference,$designation,$code_barre,$famille);
        $paginator = $this->get('knp_paginator');
        $pagination = $paginator->paginate(
                $query, $request->get('page', 1)/* page number */, 20/* limit per page */
        );
        if ($request->get('type')) {
            return $this->render('GdsArticleBundle:Article:pageList.html.twig', array('pagination' => $pagination));
        }
        return $this->render('GdsArticleBundle:Article:index.html.twig', array('pagination' => $pagination));
    }

    public function generateCodeBarreAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $articles = $em->getRepository('GdsArticleBundle:Article')->findAll();
        do {
            $code = rand(1000000000, 9999999999);
            $code = '2' . $code;
        } while ($this->codeExist($code, $articles));
        return new Response($code);
    }

    function codeExist($code, $articles) {
        foreach ($articles as $article) {
            if ($code == $article->getCodeBarre())
                return true;
        }
        return false;
    }

    public function newAction() {
        $article = new Article();
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $article->setIsSupprimer(false);
        $form = $this->createForm(new ArticleType(), $article);
        if ($request->isMethod('post')) {
            $form->bind($request);
            if ($form->isValid()) {
                $article = $form->getData();
                $em->persist($article);
                $departements = $em->getRepository('GdsArticleBundle:Departement')->findAll();
                foreach ($departements as $departement) {
                    $stock = new Stock();
                    $stock->setDepartement($departement);
                    $stock->setArticle($article);
                    $stock->setQuantiteBlanc(0);
                    $stock->setQuantiteMin(0);
                    $stock->setQuantiteNoir(0);
                    $em->persist($stock);
                }
                $em->flush();
                $red = $request->get('red');
                if ($red == 'n') {
                    $article = new Article();
                    $article->setIsSupprimer(false);
                    $form = $this->createForm(new ArticleType(), $article);
                    return $this->render('GdsArticleBundle:Article:new.html.twig', array('form' => $form->createView()));
                } else {
                    $em = $this->getDoctrine()->getEntityManager();
                    $request = $this->getRequest();
                    if ($request->get('famille')) {
                        $dql = "SELECT c FROM GdsArticleBundle:Article c WHERE (c.is_supprimer=:is_supprimer and c.reference LIKE :reference and c.designation LIKE :designation and c.code_barre LIKE :code_barre and c.famille =:famille)";
                        $query = $em->createQuery($dql)->setParameters(array('is_supprimer' => false, 'reference' => '%' . $request->get('reference') . '%', 'designation' => '%' . $request->get('designation') . '%', 'code_barre' => '%' . $request->get('code_barre') . '%', 'famille' => $request->get('famille')));
                    } else {
                        $dql = "SELECT c FROM GdsArticleBundle:Article c WHERE (c.is_supprimer=:is_supprimer and c.reference LIKE :reference and c.designation LIKE :designation and c.code_barre LIKE :code_barre)";
                        $query = $em->createQuery($dql)->setParameters(array('is_supprimer' => false, 'reference' => '%' . $request->get('reference') . '%', 'designation' => '%' . $request->get('designation') . '%', 'code_barre' => '%' . $request->get('code_barre') . '%'));
                    }
                    $paginator = $this->get('knp_paginator');
                    $pagination = $paginator->paginate(
                            $query, $request->get('page', 1)/* page number */, 10/* limit per page */
                    );
                    $pagination->setUsedRoute('gds_article_list');
                    if ($request->get('type')) {
                        return $this->render('GdsArticleBundle:Article:pageList.html.twig', array('pagination' => $pagination));
                    }
                    return $this->render('GdsArticleBundle:Article:list.html.twig', array('pagination' => $pagination));
                }
            }
        }
        return $this->render('GdsArticleBundle:Article:new.html.twig', array('form' => $form->createView()));
    }

    public function deleteAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $id = $request->get('id');
        $article = $em->getRepository('GdsArticleBundle:Article')->find($id);
        $article->setIsSupprimer(true);
        $em->persist($article);
        $em->flush();
        if ($request->get('famille')) {
            $dql = "SELECT c FROM GdsArticleBundle:Article c WHERE (c.is_supprimer=:is_supprimer and c.reference LIKE :reference and c.designation LIKE :designation and c.code_barre LIKE :code_barre and c.famille =:famille)";
            $query = $em->createQuery($dql)->setParameters(array('is_supprimer' => false, 'reference' => '%' . $request->get('reference') . '%', 'designation' => '%' . $request->get('designation') . '%', 'code_barre' => '%' . $request->get('code_barre') . '%', 'famille' => $request->get('famille')));
        } else {
            $dql = "SELECT c FROM GdsArticleBundle:Article c WHERE (c.is_supprimer=:is_supprimer and c.reference LIKE :reference and c.designation LIKE :designation and c.code_barre LIKE :code_barre)";
            $query = $em->createQuery($dql)->setParameters(array('is_supprimer' => false, 'reference' => '%' . $request->get('reference') . '%', 'designation' => '%' . $request->get('designation') . '%', 'code_barre' => '%' . $request->get('code_barre') . '%'));
        }
        $paginator = $this->get('knp_paginator');
        $pagination = $paginator->paginate(
                $query, $request->get('page', 1)/* page number */, 10/* limit per page */
        );
        $pagination->setUsedRoute('gds_article_list');
        if ($request->get('type')) {
            return $this->render('GdsArticleBundle:Article:pageList.html.twig', array('pagination' => $pagination));
        }
        return $this->render('GdsArticleBundle:Article:list.html.twig', array('pagination' => $pagination));
    }

    public function listAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        
        $reference = $request->get('reference');
        $designation = $request->get('designation');
        $code_barre = $request->get('code_barre');
        $famille = $request->get('famille');
        $query = $em->getRepository('GdsArticleBundle:Article')->getResult($reference,$designation,$code_barre,$famille);
        //$query=$em->getRepository('GdsArticleBundle:Article')->findAll();
        $paginator = $this->get('knp_paginator');
        $pagination = $paginator->paginate(
                $query, $request->get('page', 1)/* page number */, 10/* limit per page */
        );
        if ($request->get('type')) {
            return $this->render('GdsArticleBundle:Article:pageList.html.twig', array('pagination' => $pagination));
        }
        return $this->render('GdsArticleBundle:Article:list.html.twig', array('pagination' => $pagination));
    }

    public function editAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $id = $request->get('id');
        $article = $em->getRepository('GdsArticleBundle:Article')->find($id);
        $form = $this->createForm(new ArticleType(), $article);
        if ($request->isMethod('post')) {
            $form->bind($request);
            if ($form->isValid()) {
                $article = $form->getData();
                $em->persist($article);
                $em->flush();
                $em = $this->getDoctrine()->getEntityManager();
                $request = $this->getRequest();
                if ($request->get('famille')) {
                    $dql = "SELECT c FROM GdsArticleBundle:Article c WHERE (c.is_supprimer=:is_supprimer and c.reference LIKE :reference and c.designation LIKE :designation and c.code_barre LIKE :code_barre and c.famille =:famille)";
                    $query = $em->createQuery($dql)->setParameters(array('is_supprimer' => false, 'reference' => '%' . $request->get('reference') . '%', 'designation' => '%' . $request->get('designation') . '%', 'code_barre' => '%' . $request->get('code_barre') . '%', 'famille' => $request->get('famille')));
                } else {
                    $dql = "SELECT c FROM GdsArticleBundle:Article c WHERE (c.is_supprimer=:is_supprimer and c.reference LIKE :reference and c.designation LIKE :designation and c.code_barre LIKE :code_barre)";
                    $query = $em->createQuery($dql)->setParameters(array('is_supprimer' => false, 'reference' => '%' . $request->get('reference') . '%', 'designation' => '%' . $request->get('designation') . '%', 'code_barre' => '%' . $request->get('code_barre') . '%'));
                }
                $paginator = $this->get('knp_paginator');
                $pagination = $paginator->paginate(
                        $query, $request->get('page', 1)/* page number */, 10/* limit per page */
                );
                $pagination->setUsedRoute('gds_article_list');
                if ($request->get('type')) {
                    return $this->render('GdsArticleBundle:Article:pageList.html.twig', array('pagination' => $pagination));
                }
                return $this->render('GdsArticleBundle:Article:list.html.twig', array('pagination' => $pagination));
            }
        }
        return $this->render('GdsArticleBundle:Article:edit.html.twig', array('id' => $article->getId(), 'form' => $form->createView()));
    }

    public function testReferenceAction() {
        $request = $this->getRequest();
        $reference = $request->get('reference');
        $id = $request->get('id');
        if ($id) {
            $article = $this->getDoctrine()->getEntityManager()->getRepository('GdsArticleBundle:Article')->getByNotId($id, $reference);
        } else {
            $article = $this->getDoctrine()->getEntityManager()->getRepository('GdsArticleBundle:Article')->findBy(array('reference' => $reference));
        }
        if (count($article) != 0) {
            return new Response(json_encode(array('success' => 0)));
        } else {
            return new Response(json_encode(array('success' => 1)));
        }
    }

    public function testDesignationAction() {
        $request = $this->getRequest();
        $designation = $request->get('designation');
        $id = $request->get('id');
        if ($id) {
            $article = $this->getDoctrine()->getEntityManager()->getRepository('GdsArticleBundle:Article')->getByNotId($id, '', $designation);
        } else {
            $article = $this->getDoctrine()->getEntityManager()->getRepository('GdsArticleBundle:Article')->findBy(array('designation' => $designation));
        }
        if (count($article) != 0) {
            return new Response(json_encode(array('success' => 0)));
        }
        return new Response(json_encode(array('success' => 1)));
    }

    public function testCodeBarreAction() {
        $request = $this->getRequest();
        $codeBarre = $request->get('code_barre');
        $id = $request->get('id');
        if ($id) {
            $article = $this->getDoctrine()->getEntityManager()->getRepository('GdsArticleBundle:Article')->getByNotId($id, '', '', $codeBarre);
        } else {
            $article = $this->getDoctrine()->getEntityManager()->getRepository('GdsArticleBundle:Article')->findBy(array('code_barre' => $codeBarre));
        }
        if (count($article) != 0) {
            return new Response(json_encode(array('success' => 0)));
        } else {
            return new Response(json_encode(array('success' => 1)));
        }
    }

    public function refrechePageAction() {
        $request = $this->getRequest();
        $session = $request->getSession();
        $session->set('stock', $request->get('key'));
        return new Response('');
    }

    public function getAllAchatAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $fournisseur_id = $request->get('fournisseur_id');
        $fournisseur = $em->getRepository('GdsAchatBundle:Fournisseur')->find($fournisseur_id);
        $articles = $em->getRepository('GdsArticleBundle:Article')->findAll();
        $result = array();
        $k = 0;
        foreach ($articles as $article) {
            if ($article->getIsSupprimer() == false) {
                $result[$k]['designation'] = $article->getDesignation();
                $result[$k]['reference'] = $article->getReference();
                $result[$k]['taux_tva'] = $article->getTauxTva();
                $categorie_remise = $em->getRepository('GdsAchatBundle:CategorieRemiseFournisseur')->findOneBy(array('fournisseur' => $fournisseur, 'article' => $article));
                if ($categorie_remise != null) {
                    $result[$k]['remise'] = $categorie_remise->getRemise();
                    $result[$k]['prix_achat'] = $categorie_remise->getPrixUnitaireHt();
                } else {
                    $result[$k]['remise'] = 0;
                    $result[$k]['prix_achat'] = $article->getPrixAchatHt();
                }
                $name = $article->getReference() . ' : ' . $article->getDesignation();
                $result[$k]['name'] = $name;
                $result[$k]['id'] = $article->getId();
                $k++;
            }
        }
        $response = new Response(json_encode($result));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

}
